<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="采购单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseNub">
              <a-input v-model="model.purchaseNub" placeholder="请输入采购单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="采购名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入采购名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="采购部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="procurementDepartment">
              <j-select-depart v-model="model.procurementDepartment" :multi="true"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="采购人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchasingPerson">
              <j-select-user-by-dep v-model="model.purchasingPerson" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="采购日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseDate">
              <j-date placeholder="请选择采购日期" v-model="model.purchaseDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remarks">
              <a-input v-model="model.remarks" placeholder="请输入备注" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="采购附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
              <j-upload v-model="model.attachment"  ></j-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs class="bpbj-tabs" v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="采购备品备件" :key="refKeys[0]" :forceRender="true">
        <a-button style="float: left" @click="openModal"  icon="plus"  type="primary">选择备品备件</a-button>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="enePurchasingSparepartsTable.loading"
          :columns="enePurchasingSparepartsTable.columns"
          :dataSource="enePurchasingSparepartsTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="false"
          :rowSelection="true"
          :toolbar="true"
          @remove="handleTableRemove"
          :toolbarConfig="{btns:['remove']}"
          size="small"
          >
          <span style="margin-left: 8px" slot="toolbarPrefix"></span>
          <div slot="toolbarAfter" class="clearfix"></div>

        </j-vxe-table>
      </a-tab-pane>
      <j-popup-onl-report
        ref="jPopupOnlReport"
        code="ene_spare_parts"
        :multi="true"
        sorter=""
        groupId=""
        param=""
        @ok="callBack"
      />
    </a-tabs>
  </a-spin>

</template>

<script>

import {getAction, httpAction} from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JPopupOnlReport from '@/components/jeecg/modal/JPopupOnlReport'
  export default {
    name: 'EnePurchasingManagementForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
      JPopupOnlReport
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           purchaseNub: [
              { required: true, message: '请输入采购单号!'},
           ],
           name: [
              { required: true, message: '请输入采购名称!'},
           ],
           procurementDepartment: [
              { required: true, message: '请输入采购部门!'},
           ],
           purchasingPerson: [
              { required: true, message: '请输入采购人!'},
           ],
           purchaseDate: [
              { required: true, message: '请输入采购日期!'},
           ],
        },
        refKeys: ['enePurchasingSpareparts', ],
        tableKeys:['enePurchasingSpareparts', ],
        activeKey: 'enePurchasingSpareparts',
        // 采购备品备件
        enePurchasingSparepartsTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '备品备件名称',
              key: 'name',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备品备件编号',
              key: 'number',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格型号',
              key: 'model',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'unit',
              type: JVXETypes.select,
              options:[],
              dictCode:"beipin_danwei",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '数量',
              key: 'quantity',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' },{ pattern: "n", message: "${title}格式不正确" }],
            },
            {
              title: '采购单价（元）',
              key: 'price',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ pattern: "moneyNew", message: "${title}格式不正确" }],
            },
          ]
        },
        url: {
          add: "/ene/enePurchasingManagement/add",
          edit: "/ene/enePurchasingManagement/edit",
          reissue: "/ene/enePurchasingManagement/reissue",
          queryById: "/ene/enePurchasingManagement/queryById",
          enePurchasingSpareparts: {
            list: '/ene/enePurchasingManagement/queryEnePurchasingSparepartsByMainId'
          },

        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      // 触发单元格删除事件
      handleTableRemove(event) {
        let deleteIds = event.deleteRows.map(row => row.id)
        this.enePurchasingSparepartsTable.dataSource= this.enePurchasingSparepartsTable.dataSource.filter(e=>deleteIds.indexOf(e.id)==-1)
      },
      request(formData) {
        let url = this.url.add, method = 'post'
        if (this.model.id) {
          //这块重写
          if(formData.state==3){
            url = this.url.reissue
            method = 'post'
          }else {
            url = this.url.edit
            method = 'put'
          }
        }

        this.confirmLoading = true
        console.log("formData===>",formData);
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },

      callBack(rows){
      rows.forEach(column => {
        let row ={}
        row.sparepartsId=column.id
        row.name=column.name
        row.number=column.number
        row.model=column.model
        row.unit=column.unit
        console.log("+++++++++++++++++++++")
        console.log(row)
        this.enePurchasingSparepartsTable.dataSource.push(row)
      })
        console.log("===================")
        console.log(this.enePurchasingSparepartsTable.dataSource)

      },
      openModal() {
        if (this.disabled === false) {
          this.$refs.jPopupOnlReport.show()
        }
      },
      addBefore(){
        this.enePurchasingSparepartsTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.enePurchasingSpareparts.list, params, this.enePurchasingSparepartsTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          enePurchasingSparepartsList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
.clearfix {
  clear: both;
  margin-bottom: 8px;
}
.bpbj-tabs /deep/ .j-vxe-toolbar {
  margin-bottom: 0;
}
</style>